// learning-settings.js - 个性化设置组件逻辑

Component({
  data: {
    settingsExpanded: false,
    pronunciationType: 'american',
    playbackSpeed: 1.0,
    tempSpeed: 1.0,
    autoPlay: false,
    loopPlay: false,
    loopCount: '',
    loopInterval: 2
  },

  lifetimes: {
    attached() {
      // 初始化WordDataManager - 使用全局实例
      const app = getApp();
      this.wordDataManager = app.globalData.wordDataManager;
      
      // 加载发音设置
      this.loadPronunciationSettings();
    },
    
    ready() {
      // 组件初始化完成，通知父页面
      this.triggerEvent('ready');
    }
  },

  methods: {
    /**
     * 切换个性化设置展开状态
     */
    toggleSettingsPanel() {
      this.setData({
        settingsExpanded: !this.data.settingsExpanded
      });
    },

    /**
     * 加载发音设置
     */
    loadPronunciationSettings() {
      if (!this.wordDataManager) return;

      const pronunciationType = this.wordDataManager.getPronunciationType();
      const playbackSpeed = this.wordDataManager.getPlaybackSpeed();
      const autoPlay = this.wordDataManager.getAutoPlay();
      
      // 获取循环播放设置
      const settings = this.wordDataManager.getPronunciationSettings();
      const loopPlay = settings.loopPlay || false;
      const loopCount = settings.loopCount !== undefined ? settings.loopCount : '';
      const loopInterval = settings.loopInterval !== undefined ? settings.loopInterval : 2;

      this.setData({
        pronunciationType,
        playbackSpeed,
        tempSpeed: playbackSpeed,
        autoPlay,
        loopPlay,
        loopCount,
        loopInterval
      });
    },

    /**
     * 切换自动播放设置
     */
    toggleAutoPlay(e) {
      const autoPlay = !this.data.autoPlay;
      if (this.wordDataManager) {
        // 调用updatePronunciationSettings更新自动播放设置
        const success = this.wordDataManager.updatePronunciationSettings({ autoPlay });
        if (success) {
          this.setData({
            autoPlay
          });

          // 通知父页面自动播放设置已更改
          this.triggerEvent('settingchange', {
            type: 'autoPlay',
            value: autoPlay
          });

          // 添加震动反馈
          // wx.vibrateShort({
          //   type: 'light'
          // });

          wx.showToast({
            title: autoPlay ? '已开启自动播放' : '已关闭自动播放',
            icon: 'success',
            duration: 1500
          });
        }
      }
    },
    
    /**
     * 切换循环播放设置
     */
    toggleLoopPlay(e) {
      const loopPlay = !this.data.loopPlay;
      if (this.wordDataManager) {
        // 调用updatePronunciationSettings更新循环播放设置
        const success = this.wordDataManager.updatePronunciationSettings({ loopPlay });
        if (success) {
          this.setData({
            loopPlay
          });

          // 通知父页面循环播放设置已更改
          this.triggerEvent('settingchange', {
            type: 'loopPlay',
            value: loopPlay
          });

          wx.showToast({
            title: loopPlay ? '已开启循环播放' : '已关闭循环播放',
            icon: 'success',
            duration: 1500
          });
        }
      }
    },
    
    /**
     * 处理循环次数变化
     */
    onLoopCountChange(e) {
      const value = e.detail.value;
      // 验证输入值，只允许数字或空字符串
      if (value === '' || !isNaN(value) && parseInt(value) >= 0) {
        // 保存设置但不立即触发事件，等待用户确认或间隔输入
        this.loopCountInput = value;
        
        // 延迟保存和触发事件，避免频繁保存
        if (this.loopCountTimer) {
          clearTimeout(this.loopCountTimer);
        }
        
        this.loopCountTimer = setTimeout(() => {
          if (this.wordDataManager) {
            const count = this.loopCountInput === '' ? '' : parseInt(this.loopCountInput);
            const success = this.wordDataManager.updatePronunciationSettings({ loopCount: count });
            if (success) {
              this.setData({
                loopCount: count
              });
              
              // 通知父页面循环次数已更改
              this.triggerEvent('settingchange', {
                type: 'loopCount',
                value: count
              });
            }
          }
          this.loopCountTimer = null;
        }, 500);
      }
    },
    
    /**
     * 处理循环间隔变化
     */
    onLoopIntervalChange(e) {
      const value = e.detail.value;
      // 验证输入值，只允许数字或空字符串
      if (value === '' || (!isNaN(value) && parseFloat(value) >= 0)) {
        // 保存设置但不立即触发事件，等待用户确认或间隔输入
        this.loopIntervalInput = value;
        
        // 延迟保存和触发事件，避免频繁保存
        if (this.loopIntervalTimer) {
          clearTimeout(this.loopIntervalTimer);
        }
        
        this.loopIntervalTimer = setTimeout(() => {
          if (this.wordDataManager) {
            const interval = this.loopIntervalInput === '' ? 2 : parseFloat(this.loopIntervalInput);
            const success = this.wordDataManager.updatePronunciationSettings({ loopInterval: interval });
            if (success) {
              this.setData({
                loopInterval: interval
              });
              
              // 通知父页面循环间隔已更改
              this.triggerEvent('settingchange', {
                type: 'loopInterval',
                value: interval
              });
            }
          }
          this.loopIntervalTimer = null;
        }, 500);
      }
    },

    /**
     * 切换发音方式
     */
    togglePronunciationType(e) {
      const type = e.currentTarget.dataset.type;
      if (type && this.wordDataManager) {
        // 调用updatePronunciationSettings更新发音类型
        const success = this.wordDataManager.updatePronunciationSettings({ pronunciationType: type });
        if (success) {
          this.setData({
            pronunciationType: type
          });

          // 通知父页面发音类型已更改
          this.triggerEvent('settingchange', {
            type: 'pronunciationType',
            value: type
          });

          // 添加音效反馈
          // wx.vibrateShort({
          //   type: 'light'
          // });

          wx.showToast({
            title: `已切换到${type === 'american' ? '美式' : '英式'}发音`,
            icon: 'success',
            duration: 1500
          });
        }
      }
    },

    /**
     * 设置播放倍速
     */
    setSpeed(e) {
      const speed = parseFloat(e.currentTarget.dataset.speed);
      if (!isNaN(speed) && this.wordDataManager) {
        // 验证倍速范围并保留两位小数
        const validSpeed = Math.round(Math.max(0.5, Math.min(2.0, speed)) * 100) / 100;
        // 调用updatePronunciationSettings更新播放速度
        const success = this.wordDataManager.updatePronunciationSettings({ playbackSpeed: validSpeed });
        if (success) {
          this.setData({
            playbackSpeed: validSpeed,
            tempSpeed: validSpeed
          });

          // 通知父页面播放速度已更改
          this.triggerEvent('settingchange', {
            type: 'playbackSpeed',
            value: validSpeed
          });
          
          // 触发播放发音
          this.triggerEvent('playsound', {});

          // 添加音效反馈
          // wx.vibrateShort({
          //   type: 'light'
          // });

          wx.showToast({
            title: `已设置${validSpeed}x倍速`,
            icon: 'success',
            duration: 1500
          });
        }
      }
    },

    /**
     * 滑块倍速变化（拖拽中）
     */
    onSpeedChanging(e) {
      const speed = parseFloat(e.detail.value);
      if (!isNaN(speed)) {
        // 限制倍速范围在0.5-2.0之间，并保留两位小数
        const validSpeed = Math.round(Math.max(0.5, Math.min(2.0, speed)) * 100) / 100;

        // 只更新临时值，不保存到存储
        this.setData({
          tempSpeed: validSpeed
        });
      }
    },

    /**
     * 滑块倍速变化（拖拽结束）
     */
    onSpeedChange(e) {
      let speed = parseFloat(e.detail.value);
      if (isNaN(speed)) {
        speed = 1.0; // 默认值
      }

      // 限制倍速范围在0.5-2.0之间，并保留两位小数
      speed = Math.round(Math.max(0.5, Math.min(2.0, speed)) * 100) / 100;

      if (this.wordDataManager) {
        // 调用updatePronunciationSettings更新播放速度
        const success = this.wordDataManager.updatePronunciationSettings({ playbackSpeed: speed });
        if (success) {
          this.setData({
            playbackSpeed: speed,
            tempSpeed: speed // 同步临时值
          });
          
          // 通知父页面播放速度已更改
          this.triggerEvent('settingchange', {
            type: 'playbackSpeed',
            value: speed
          });
          
          // 触发播放发音
          this.triggerEvent('playsound', {});
        }
      }
    },
  }
});